import * as React from 'react';
import { get, map, pick } from 'lodash';
import { Tooltip, Icon, Popconfirm, message, Radio } from 'antd';
import makeHoc from 'components/common/makeHoc';
import CONFIG from 'constants/config';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/knowledge';

import { saveKnowledgeImages } from 'actions/knowledge';

import LoadableComponent from 'components/common/LoadableComponent';
const LoadablePopToSelect = LoadableComponent(() => import('pages/attachment/PopToSelect'));

interface EditImageProps {
  dispatch: (action: any) => any;
  handleCallback: (covers: any[]) => any;
  covers: any[];
  selectedItems: any[];
  loadingGroup: any;
  selectMax?: number;
}

interface EditImageState {
  isSelectImage: boolean;
}
class EditImage extends React.Component<EditImageProps, EditImageState> {
  static defaultProps: EditImageProps = {
    dispatch: () => {},
    handleCallback: () => {},
    covers: [],
    selectedItems: [],
    loadingGroup: {},
    selectMax: 3,
  };
  constructor(props: EditImageProps) {
    super(props);
    this.state = {
      isSelectImage: false,
    };
  }

  handleCloseModal = () => {
    this.setState({
      isSelectImage: false,
    });
  };

  handleOpenModal = () => {
    this.setState({
      isSelectImage: true,
    });
  };

  ConfirmToDelete(props: any) {
    return (
      <Popconfirm
        okText="确定"
        cancelText="取消"
        title="你确定要删除此图片吗？"
        onConfirm={props.onRemove}>
        <Icon type="close" />
      </Popconfirm>
    );
  }

  // 如果只剩下一张图片，则自动为默认
  handleRemoveImage(imageId: number) {
    const { covers, handleCallback } = this.props;
    let leftImages = covers.filter((item: any) => {
      return item.id !== imageId;
    });
    if (leftImages.length === 1) {
      leftImages[0]['isCover'] = true;
    }

    handleCallback(leftImages);
  }

  // 如果没有设置封面图片，则设置第一张
  handleSubmit = () => {
    const { selectedItems, handleCallback } = this.props;
    const cover = selectedItems.find((item: any) => {
      const isCover = get(item, 'isCover', false);
      return isCover === true;
    });
    if (!cover) {
      selectedItems[0]['isCover'] = true;
    }

    handleCallback(selectedItems);
    this.handleCloseModal();
  };

  // 设置默认(封面)图片
  handleRadioChange = (e: any) => {
    const { covers, handleCallback } = this.props;
    const imageId = e.target.value;

    const data = covers.map((item: any) => {
      item['isCover'] = item.id === imageId;
      return item;
    });

    handleCallback(data);
  };

  renderItems = (): any => {
    const { covers } = this.props;
    if (covers.length === 0) {
      return (
        <p className="loading-placeholder">
          <Icon type="frown-o" />
          &nbsp;还没有数据，&nbsp;
          <a href="javascript:void(0);" onClick={this.handleOpenModal}>
            <Icon type="plus" />
            添加
          </a>
        </p>
      );
    }

    const frontImage = covers.find((item: any) => {
      return item.isCover === true;
    });

    return (
      <Radio.Group
        name="frontImage"
        style={{ display: 'block' }}
        value={get(frontImage, 'id', 0)}
        onChange={this.handleRadioChange}>
        {covers.map((item: any) => {
          return (
            <div key={item.id} className="classic-upload-item">
              <div className="classic-thumbnail">
                <Tooltip title="设置为默认(封面)图片">
                  <Radio value={item.id} style={{ marginTop: -20 }} />
                </Tooltip>
                <img src={item.uri} style={{ display: 'inline-block' }} />
              </div>
              <div className="classic-operation">
                <this.ConfirmToDelete
                  onRemove={() => {
                    this.handleRemoveImage(item.id);
                  }}
                />
              </div>
            </div>
          );
        })}
      </Radio.Group>
    );
  };

  render() {
    const { covers, selectMax } = this.props;
    const { isSelectImage } = this.state;

    return (
      <div>
        {isSelectImage && (
          <LoadablePopToSelect
            title="请选择三张图片"
            ownItems={covers}
            selectMax={selectMax}
            selectType={CONFIG.ITEM_IMAGE}
            onCancel={this.handleCloseModal}
            onOk={this.handleSubmit}
          />
        )}
        {this.renderItems()}
      </div>
    );
  }
}

interface OwnProps {
  covers: any[];
  handleCallback: (covers: any[]) => any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { loadingGroup } = state;
  const { selectedItems } = state.attachment;
  const { covers, handleCallback } = ownProps;
  return {
    loadingGroup,
    covers,
    handleCallback,
    selectedItems,
  };
}

export default makeHoc(mapStateToProps)(EditImage, {
  addImage() {
    this.handleOpenModal();
  },
});
